<?php
/**
 * 校验Token
 *
 * @author  
 * @time 2024-01-18 15:15:23
 */

namespace App\Http\Middleware;

use App\Facades\Response;
use App\Services\AuthToken;
use Closure;
use Illuminate\Support\Facades\Auth;

class AuthJwt
{
    /**
     * 校验token
     *
     * @param $request
     * @param Closure $next
     * @return mixed
     * @author  
     * @time 2024-01-18 15:21:24
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('Token') ?: $request->input('token') ?: $request->cookie('token');

        if (empty($token)) {
            return Response::fail('Token参数为空！', [], 401);
        }

        try {
            if (!$userId = AuthToken::checkJwt($token)) {
                return Response::fail('登录已过期，请重新登录！', [], 401);
            }
        } catch (\Exception $e) {
            return Response::fail('登录已过期，请重新登录！', [], 401);
        }


        foreach ($request->keys() as $key) {
            if ($request->get($key) === 'null') {
                $request->request->remove($key);
            }
        }

//        $loginRet = Auth::loginUsingId($userId);
//        if ($loginRet === false) {
//            return Response::fail('登录异常，请重新登录！', [], 401);
//        }


        return $next($request);
    }

}